import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper'

interface UserInfo {
  name: string
  age: number
}

const HomeView = () => {
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null)
  const [newUserName, setNewUserName] = useState('')
  const [newUserAge, setNewUserAge] = useState<number | null>(null)

  // 获取全局状态
  const getGlobalState = () => {
    const globalState = (window as any).__MICRO_APP_ENVIRONMENT__?.globalState
    if (globalState && globalState.userInfo) {
      setUserInfo(globalState.userInfo)
      setNewUserName(globalState.userInfo.name)
      setNewUserAge(globalState.userInfo.age)
    }
  }

  // 更新用户信息
  const updateUserInfo = () => {
    if (newUserName && newUserAge !== null) {
      const globalState = (window as any).__MICRO_APP_ENVIRONMENT__?.globalState
      if (globalState?.actions) {
        globalState.actions.setGlobalState({
          userInfo: {
            name: newUserName,
            age: newUserAge
          }
        })
      }
      console.log('用户信息已更新:', { name: newUserName, age: newUserAge })
    }
  }

  // 监听全局状态变化
  useEffect(() => {
    getGlobalState()
    
    const globalState = (window as any).__MICRO_APP_ENVIRONMENT__?.globalState
    let cleanup = () => {}
    
    if (globalState?.actions) {
      const result = globalState.actions.onGlobalStateChange((state: any) => {
        if (state.userInfo && JSON.stringify(state.userInfo) !== JSON.stringify(userInfo)) {
          setUserInfo(state.userInfo)
          setNewUserName(state.userInfo.name)
          setNewUserAge(state.userInfo.age)
        }
      }, true)
      
      // 确保只在result是函数时才赋值
      if (typeof result === 'function') {
        cleanup = result
      }
    }

    return () => {
      // 确保cleanup是一个函数
      if (typeof cleanup === 'function') {
        cleanup()
      }
    }
  }, [userInfo])

  // 检查是否在qiankun环境中运行
  const isInQiankun = qiankunWindow.__POWERED_BY_QIANKUN__

  return (
    <div className="home">
      <h2>App3 - Home Page</h2>
      
      {/* 只有在独立运行时才显示导航 */}
      {!isInQiankun && (
        <nav>
          <Link to="/app3/home">Home</Link>
          <Link to="/app3/about">About</Link>
        </nav>
      )}
      
      <div className="info-section">
        <h3>从主应用接收的用户信息：</h3>
        <p>用户名：{userInfo?.name}</p>
        <p>年龄：{userInfo?.age}</p>
      </div>
      
      <div className="interaction-section">
        <h3>修改用户信息：</h3>
        <div className="form-group">
          <label>用户名：</label>
          <input 
            value={newUserName} 
            onChange={(e) => setNewUserName(e.target.value)} 
            type="text" 
          />
        </div>
        <div className="form-group">
          <label>年龄：</label>
          <input 
            value={newUserAge || ''} 
            onChange={(e) => setNewUserAge(parseInt(e.target.value))} 
            type="number" 
          />
        </div>
        <button onClick={updateUserInfo}>更新用户信息（传递给主应用）</button>
      </div>
      
      <div className="tips">
        <p>💡 提示：修改用户信息后，切换到其他子应用，查看数据是否同步更新</p>
      </div>
    </div>
  )
}

export default HomeView